import {Link} from 'umi';
// @ts-ignore
import BpmnViewer from 'bpmn-js/lib/NavigatedViewer';
// import MoveModule from 'diagram-js/lib/features/move'
// @ts-ignore
import TouchModule from 'diagram-js/lib/navigation/touch'
// @ts-ignore
import ModelingModule from 'bpmn-js/lib/features/modeling'
// @ts-ignore
import MoveCanvasModule from 'diagram-js/lib/navigation/movecanvas'
import {notification,Card } from "antd";
import {useEffect, useState} from "react";
import styles from "@/components/Bpmn/ProcessManage/BpmnEditor/sources/Bpmn.less";
import styles_index from './index.less';
import EditingTools from "@/components/Bpmn/ProcessManage/BpmnEditor/EditingTools";
import FullModal from "@/components/Bpmn/widgets/FullModal";
import magicModdleDescriptor from "@/components/Bpmn/ProcessManage/custom-properties-panel/descriptors/magic.json";
const CustomDiagramViewer = (
    {
        id,
        value,
    }:{
        id:string;
        value?:string;
    }
) => {


    const [ svgVisible,setSvgVisible ] = useState(false);
    const [ svgSrc,setSvgSrc ] = useState("");
    const [ scale,setScale ] = useState(1);
    const [ bpmnViewer,setBpmnViewer ] = useState(null);
    const [ knowledgeName,setKnowledgeName ] = useState("");
    const [ knowledgeId,setKnowledgeId ] = useState("");
    const [ nodeId,setNodeId ] = useState("");
    const [ nodeName,setNodeName ] = useState("");

    useEffect(()=>{
        if(value){
            initBpmn(value);
        }
    },[value])

    const initBpmn = (xml:string) => {
       const _bpmnViewer= new BpmnViewer({
            container: `#canvas_${id}`,
            height: '100%',
            width: '100%',
            additionalModules: [
                // MoveModule, // 可以调整元素
                ModelingModule, // 基础工具 MoveModule、SetColor 等依赖于此
                MoveCanvasModule, // 移动整个画布
                TouchModule
            ],
           moddleExtensions: {
               magic: magicModdleDescriptor,
           },
        });
        _bpmnViewer.on('element.click', (e:any) => {
            setKnowledgeId(e.element.businessObject.knowledgeId);
            setKnowledgeName(e.element.businessObject.knowledgeName);
            setNodeId(e.element.businessObject.id);
            setNodeName(e.element.businessObject.name);

        })


        setBpmnViewer(_bpmnViewer);
        renderDiagram(xml,_bpmnViewer);
    }

    // 渲染 xml 格式
   const renderDiagram = (xml:string,viewer:any) => {
        if(viewer){
            // @ts-ignore
            viewer.importXML(xml, (err:any) => {
                // 调整在正中间
                viewer.get('canvas').zoom('fit-viewport', 'auto')
                if (err) {
                    notification.error({
                        message: '提示',
                        description: '导入失败',
                    });
                }
            });
        }
    };
        //全图
    const handleFit=()=>{
        if(bpmnViewer){
            // @ts-ignore
            const bpmnCanvas = bpmnViewer.get('canvas')
            bpmnCanvas.zoom('fit-viewport', 'auto')
        }
    }

    // 关闭流程图弹窗
    const handleCancel = () => {
        setSvgVisible(false);
        setSvgSrc("");
    };

    // 预览图片
    const handlePreview = () => {
        if(bpmnViewer){
            // @ts-ignore
            bpmnViewer.saveSVG({ format: true }, (err:any, data:any) => {
                setSvgVisible(true);
                setSvgSrc(data);
            });
        }
    };

    // 流程图放大缩小
    const handleZoom = (radio?:any) => {
        const newScale = !radio
            ? 1.0 // 不输入radio则还原
            : scale + radio <= 0.2 // 最小缩小倍数
                ? 0.2
                : scale + radio;
        if(!radio){
            handleFit();
        }
        if(bpmnViewer){
            // @ts-ignore
            bpmnViewer.get('canvas').zoom(newScale);
            setScale(newScale);
        }
    };

    return (
        <div
            style={{ width: '100%', height: '600px' }}
        >
            <div className={styles.container}>
                <div className={styles.canvas} id={`canvas_${id}`}/>
                <EditingTools
                    editingToolsStyle={styles_index.editingTools}
                    onZoomReset={() => handleZoom()}
                    onZoomIn={() => handleZoom(0.1)}
                    onZoomOut={() => handleZoom(-0.1)}
                    onPreview={handlePreview}
                />
                <div className={styles_index.tooltip}>
                    <div>缩放:  Ctrl+鼠标滚轮</div>
                    <div>滚动（纵向）:  鼠标滚轮</div>
                    <div>滚动（横向）:  Shift+鼠标滚轮</div>
                </div>

                {
                    knowledgeId &&
                    <div className={styles_index.internal}>
                        <Card
                            title={
                                <div>
                                    <div style={{fontSize:14,fontWeight:"bold"}}>{nodeName}</div>
                                    <div style={{color:"#c1c1c1"}}>[{nodeId}]</div>
                                </div>
                            }
                            size="small">
                            <div style={{maxWidth:300}}>
                                <Link target="_blank" to={`/knowledge/details/${knowledgeId}`}>{knowledgeName}</Link>
                            </div>
                        </Card>
                    </div>
                }


            </div>
            {svgVisible && (
                <FullModal visible={svgVisible} onCancel={handleCancel}>
                    <div
                        dangerouslySetInnerHTML={{
                            __html: svgSrc,
                        }}
                    />
                </FullModal>
            )}
        </div>
    )
}

export default CustomDiagramViewer;